package com.tzkyzj.tiremanagersystem.ui;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.android.material.button.MaterialButton;
import com.tzkyzj.tiremanagersystem.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PhotoDetailActivity extends AppCompatActivity {

    private static final int REQUEST_WRITE_STORAGE = 1001;

    private List<String> photoUrls;
    private int currentPosition;
    private ImageView ivPhoto;
    private MaterialButton btnSave, btnPrevious, btnNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_detail);

        initViews();
        getIntentData();
        setupClickListeners();
        displayCurrentPhoto();
    }

    private void initViews() {
        ivPhoto = findViewById(R.id.ivPhoto);
        btnSave = findViewById(R.id.btnSave);
        btnPrevious = findViewById(R.id.btnPrevious);
        btnNext = findViewById(R.id.btnNext);
    }

    private void getIntentData() {
        Intent intent = getIntent();
        photoUrls = intent.getStringArrayListExtra("photoUrls");
        currentPosition = intent.getIntExtra("currentPosition", 0);

        if (photoUrls == null || photoUrls.isEmpty()) {
            Toast.makeText(this, "照片数据错误", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void setupClickListeners() {
        btnSave.setOnClickListener(v -> savePhotoToGallery());
        btnPrevious.setOnClickListener(v -> showPreviousPhoto());
        btnNext.setOnClickListener(v -> showNextPhoto());

        // 可选：添加显示/隐藏控制按钮的功能
        ivPhoto.setOnClickListener(v -> toggleControls());
    }

    // 可选：添加控制按钮显示/隐藏的方法
    private void toggleControls() {
        int visibility = btnSave.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE;
        btnSave.setVisibility(visibility);
        btnPrevious.setVisibility(visibility);
        btnNext.setVisibility(visibility);
    }

    private void displayCurrentPhoto() {
        if (photoUrls != null && currentPosition >= 0 && currentPosition < photoUrls.size()) {
            String photoUrl = photoUrls.get(currentPosition);

            Glide.with(this)
                    .load(photoUrl)
                    .into(ivPhoto);

            // 更新按钮状态
            btnPrevious.setEnabled(currentPosition > 0);
            btnNext.setEnabled(currentPosition < photoUrls.size() - 1);

            // 更新标题
            setTitle("照片 " + (currentPosition + 1) + "/" + photoUrls.size());
        }
    }

    private void showPreviousPhoto() {
        if (currentPosition > 0) {
            currentPosition--;
            displayCurrentPhoto();
        }
    }

    private void showNextPhoto() {
        if (currentPosition < photoUrls.size() - 1) {
            currentPosition++;
            displayCurrentPhoto();
        }
    }

    private void savePhotoToGallery() {
        // 检查权限
        if (checkStoragePermission()) {
            performSavePhoto();
        } else {
            requestStoragePermission();
        }
    }

    private boolean checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 使用 MANAGE_EXTERNAL_STORAGE
            return Environment.isExternalStorageManager();
        } else {
            // Android 10及以下使用 WRITE_EXTERNAL_STORAGE
            return ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void requestStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 请求所有文件访问权限
            Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
            startActivity(intent);
        } else {
            // Android 10及以下请求写入权限
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_WRITE_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                performSavePhoto();
            } else {
                Toast.makeText(this, "需要存储权限才能保存照片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void performSavePhoto() {
        if (photoUrls == null || currentPosition < 0 || currentPosition >= photoUrls.size()) {
            return;
        }

        String photoUrl = photoUrls.get(currentPosition);

        try {
            // 使用 DownloadManager 下载图片
            DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(photoUrl));

            // 设置下载目录和文件名
            String fileName = "tire_photo_" + System.currentTimeMillis() + ".jpg";
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,
                    "TireManager/" + fileName);

            // 设置通知可见性
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("保存轮胎照片");
            request.setDescription("正在下载照片...");

            // 开始下载
            downloadManager.enqueue(request);

            Toast.makeText(this, "照片已开始下载到相册", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}